package cn.hd.authorService.service.author.impl;

import cn.hd.authorService.service.author.LoginService;
import cn.hd.authorService.utils.JwtUtil;
import cn.hd.authorService.utils.RedisCache;
import cn.hd.authorService.vo.LoginUser;
import cn.hd.commonService.entity.SysUser;
import cn.hd.commonService.exception.CustomException;
import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.CircleCaptcha;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.StrUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private RedisCache redisCache;

    @Override
    public Map<String, Object> login(SysUser user,String imageCode) {
        //AuthenticationManager authenticate进行用户认证
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(user.getAccount(),user.getPassword());
        Authentication authenticate = authenticationManager.authenticate(authenticationToken);
        //如果认证没通过，给出对应的提示
        if(Objects.isNull(authenticate)){
            throw new CustomException("账号或密码错误");
        }
        String code = Convert.toStr(redisCache.getCacheObject("ImageCode:" + imageCode.toLowerCase()));
        if (StrUtil.isBlankIfStr(code)){
            throw new CustomException("验证码错误");
        }
        //如果认证通过了，使用userid生成一个jwt jwt存入ResponseResult返回
        LoginUser loginUser = (LoginUser) authenticate.getPrincipal();
        Integer userid = loginUser.getUser().getRecordId();
        //一个小时过期
        String jwt = JwtUtil.createJWT(Convert.toStr(userid));
        //把完整的用户信息存入redis  userid作为key（一个小时过期）
        redisCache.setCacheObject("login:"+userid,loginUser,1,TimeUnit.HOURS);
        //返回数据
        Map<String,Object> map = new HashMap<>();
        map.put("token",jwt);
        map.put("user",loginUser.getUser());
        map.put("permissions",loginUser.getPermissions());
        return map;
    }

    @Override
    public void logout() {
        //获取SecurityContextHolder中的用户id
        UsernamePasswordAuthenticationToken authentication = (UsernamePasswordAuthenticationToken) SecurityContextHolder.getContext().getAuthentication();
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        String userid = Convert.toStr(loginUser.getUser().getRecordId());
        //删除redis中的值
        redisCache.deleteObject("login:"+userid);
    }

    /**
     * 获取图片验证码
     * @return
     */
    @Override
    public Map<String,String> getImageCode() throws IOException {
        Map<String, String> data = new HashMap<>();
        CircleCaptcha captcha = CaptchaUtil.createCircleCaptcha(200, 100, 4, 20);
        data.put("image",captcha.getImageBase64());
        //将获取到的验证码缓存到redis
        redisCache.setCacheObject("ImageCode:"+captcha.getCode().toLowerCase(),captcha.getImageBase64(),1000*10*3, TimeUnit.MILLISECONDS);
        data.put("code",captcha.getCode().toLowerCase());
        return data;
    }
}
